package com.hqj.demo.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * spring 类注解的练习05
 * @author HQJ
 * 1、一个普通类ListClass,有一个方法addList(),参数是String name
 *   有一个方法findList(),返回List<String>集合
 *
 * 2、有一个ListDao 类，数据持久层，
 *  有一个方法addList(),参数是String name，调用ListClass，添加值
 *  有一个方法findList(),返回List<String>集合
 *
 * 3、有一个ListService 类，数据逻辑，
 *  有一个方法addList(),参数是String name，调用ListDao，
 *  添加值(List存放的值不能重复，如果重复，返回已存在，否则存放成功)
 *  有一个方法findList(),返回List<String>集合
 *
 * 4、ListController 类，控制层
 *  有一个方法addList(),参数是String name，调用ListService，添加值
 *  有一个方法findList(),返回List<String>集合
 *
 * 5、Exercise05测试类，添加n个值，过5秒后，输出集合中的字符串
 */
public class Exercise05 {

    public static void main(String[] args) {

        //读取spring的配置文件
        ApplicationContext ac =
                new ClassPathXmlApplicationContext("com/hqj/demo/spring05.xml");

        ListController lc = (ListController)ac.getBean("listController");
        Scanner scan = new Scanner(System.in);
        for(int i=0;i<5;i++){
            System.out.println("请输入第"+(i+1)+"个名称:");
            String name = scan.next();

            System.out.println(lc.addList(name));
        }
        System.out.println("-------------------------\n输出完成的名字为:");
        for(String name:lc.findList()){
            System.out.println(name+"\t");
        }
        System.out.println("----------------------");
    }

}
@Component
class ListClass{
    List<String> list = new ArrayList<>();
    public void addList(String name){
        list.add(name);
    }

    public List<String> findList(){
        return list;
    }
}
@Repository
class ListDao{
    @Autowired
    private ListClass lc;

    public void addList(String name){
        lc.addList(name);
    }

    public List<String> findList(){
        return lc.findList();
    }
}
@Service
class ListService{
    @Autowired
    private ListDao ld;

    public String addList(String name){
        for(String n:ld.findList()){
            if(n.equals(name)){
                return "内容\'"+name+"\'已经存在";
            }
        }

        ld.addList(name);
        return "存放成功";
    }

    public List<String> findList(){
        return ld.findList();
    }
}

@Controller
class ListController{
    @Resource(name="listService")
    private ListService ls;

    public String addList(String name){
        return ls.addList(name);
    }

    public List<String> findList(){
        return ls.findList();
    }

}